package cn.krund.lyc.hotlerobot.activity.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.krund.lyc.hotlerobot.R;
import cn.krund.lyc.hotlerobot.activity.base.BaseActivity;
import cn.krund.lyc.hotlerobot.wifimanage.MyWifiAdapter;
import cn.krund.lyc.hotlerobot.wifimanage.PutInfoToMap;
import cn.krund.lyc.hotlerobot.wifimanage.WifiAdmin;
import cn.krund.lyc.hotlerobot.wifimanage.WifiConnDialog;
import cn.krund.lyc.hotlerobot.wifimanage.WifiStateDialog;
import cn.krund.lyc.hotlerobot.wifimanage.WifiUserInfo;

/**
 * @包名: cn.krund.lyc.hotlerobot.activity.ui
 * @作者: 刘育成
 * @时间: 2018/3/27  11:09
 * @org: 克路德人工智能
 * @描述: TODO
 * @fileName: WifiFunctionActivity
 */

public class WifiFunctionActivity extends BaseActivity {
    private static final int REFRESH_CONN = 100;
    protected static boolean isUpDate = true;                       // 是否更新
    private ListView m_wifiList;                                    // wifi列表
    private ImageView iv_wifi_open, iv_wifi_background_icon;         // wifi开关
    private TextView tv_wifi_title, tv_back, tv_title;
    public static WifiAdmin m_wifiAdmin;                                  // wifi管理类
    private List<ScanResult> m_scanResultList = new ArrayList<>();  // 扫描到的wifi列表
    public static MyWifiAdapter m_wifiAdapter;
    private boolean isOpenWifi;                                     // 是否打开wifi
    private WifiUserInfo wui;
    public static Map<String, WifiUserInfo> getInfoMap;             // 保存已经连接过得wifi信息
    public static boolean delete;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wifi_function;
    }

    @Override
    protected void initView() {
        m_wifiAdmin = new WifiAdmin(this);
        wui = new WifiUserInfo();

        getWifiListInfo(); // 获取wifi列表
        refreshWifiStatusOnTime();
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        m_wifiList = (ListView) findViewById(R.id.wifiListView);
        iv_wifi_open = (ImageView) findViewById(R.id.iv_wifi_open_icon);
        iv_wifi_background_icon = (ImageView) findViewById(R.id.iv_wifi_background_icon);
        tv_wifi_title = (TextView) findViewById(R.id.tv_wifi_title);
        checkWifiState();
        m_wifiAdapter = new MyWifiAdapter(this, m_scanResultList);
        m_wifiList.setAdapter(m_wifiAdapter);
        iv_wifi_open.setOnClickListener(m_wifiSwitchListenner);
        m_wifiList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final ScanResult scanResult = m_scanResultList.get(position);
                AlertDialog.Builder builder = new AlertDialog.Builder(WifiFunctionActivity.this);
                builder.setTitle("忘记该网络")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (getInfoMap != null) {
                                    getInfoMap.remove(scanResult.SSID);//将此wifi忘记
                                    delete = true;
                                    PutInfoToMap.putMap(WifiFunctionActivity.this, "wifiInfo", getInfoMap);
                                }
                                delete = false;
                            }
                        }).setNegativeButton("否", null).show();
                return false;
            }
        });
        m_wifiList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ScanResult scanResult = m_scanResultList.get(position);

                String desc = "";
                String descOri = scanResult.capabilities;
                if (descOri.toUpperCase().contains("WPA-PSK")) {
                    desc = "WPA";
                }
                if (descOri.toUpperCase().contains("WPA2-PSK")) {
                    desc = "WPA2";
                }
                if (descOri.toUpperCase().contains("WPA-PSK")
                        && descOri.toUpperCase().contains("WPA2-PSK")) {
                    desc = "WPA/WPA2";
                }

                if (desc.equals("")) {
                    isConnectSelf(scanResult);
                    return;
                }
                isUpDate = true;
                refreshWifiStatusOnTime();
                isConnect(scanResult);
            }
        });
    }

    private void isConnect(final ScanResult scanResult) {
        if (m_wifiAdmin.isCoonnct(scanResult)) {
            // 已连接，显示连接状态对话框
            WifiStateDialog mStatusDialog = new WifiStateDialog(
                    WifiFunctionActivity.this, R.style.PopDialog, scanResult
            );
            mStatusDialog.show();
        } else {
            if (getInfoMap != null) {
                for (Map.Entry<String, WifiUserInfo> entry : getInfoMap.entrySet()) {
                    wui = entry.getValue();
                    if (scanResult.SSID.equals(wui.getName())) {
                        Toast.makeText(WifiFunctionActivity.this, "正在进行身份验证...", Toast.LENGTH_LONG).show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                m_wifiAdmin.connect(scanResult.SSID, wui.getPassword(), wui.getType());
                            }
                        }).start();
                        return;
                    }
                }
            }
            // 未连接显示连接输入对话框
            WifiConnDialog mDialog = new WifiConnDialog(
                    WifiFunctionActivity.this, R.style.PopDialog, scanResult);
            mDialog.show();
        }
    }

    private void isConnectSelf(ScanResult scanResult) {
        if (m_wifiAdmin.isCoonnct(scanResult)) {
            // 已连接，显示连接状态对话框
            WifiStateDialog mStatusDialog = new WifiStateDialog(
                    WifiFunctionActivity.this, R.style.PopDialog, scanResult);
            mStatusDialog.show();

        } else {
            //连接特殊wifi:例如没有密码
            boolean iswifi = m_wifiAdmin.connectSpecificAP(scanResult);
            if (iswifi) {
                isUpDate = true;
                refreshWifiStatusOnTime();
                Toast.makeText(WifiFunctionActivity.this, "连接成功！", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(WifiFunctionActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
            }

        }
    }

    // wifi开关的监听
    View.OnClickListener m_wifiSwitchListenner = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            m_scanResultList.clear();
            if (isOpenWifi) {
                m_wifiAdmin.closeWifi();//关闭wifi
                iv_wifi_open.setBackgroundResource(R.drawable.wifi_close);
                iv_wifi_background_icon.setVisibility(View.VISIBLE);
                tv_wifi_title.setVisibility(View.VISIBLE);
                isUpDate = false;
                isOpenWifi = false;
            } else {
                m_wifiAdmin.openWifi();
                isUpDate = true;
                isOpenWifi = true;
                iv_wifi_open.setBackgroundResource(R.drawable.wifi_open);
                iv_wifi_background_icon.setVisibility(View.GONE);
                tv_wifi_title.setVisibility(View.GONE);
                refreshWifiStatusOnTime();
            }
        }
    };

    // 检查wifi的开关状态
    private void checkWifiState() {
        int wifiState = m_wifiAdmin.checkState();
        if (wifiState == WifiManager.WIFI_STATE_DISABLED
                || wifiState == WifiManager.WIFI_STATE_DISABLING
                || wifiState == WifiManager.WIFI_STATE_UNKNOWN) {
            iv_wifi_open.setBackgroundResource(R.drawable.wifi_close);
            isOpenWifi = false;
        } else {
            iv_wifi_open.setBackgroundResource(R.drawable.wifi_open);
            iv_wifi_background_icon.setVisibility(View.GONE);
            tv_wifi_title.setVisibility(View.GONE);
            isOpenWifi = true;
        }
    }

    /**
     * 定时刷新Wifi列表信息
     */
    public void refreshWifiStatusOnTime() {
        new Thread() {
            @Override
            public void run() {
                while (isUpDate) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessage(REFRESH_CONN);
                }
            }
        }.start();
    }

    private Handler mHandler = new MyHandler(this);

    public static class MyHandler extends Handler {
        WeakReference<WifiFunctionActivity> reference;

        public MyHandler(WifiFunctionActivity activity) {
            this.reference = new WeakReference<WifiFunctionActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WifiFunctionActivity activity = reference.get();
            switch (msg.what) {
                case REFRESH_CONN:
                    activity.getWifiListInfo();
                    activity.m_wifiAdapter.setDatas(activity.m_scanResultList);
                    activity.m_wifiAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void initNev() {
        tv_title.setText("WIFI设置");
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void getWifiListInfo() {
        m_wifiAdmin.startScan();
        getInfoMap = PutInfoToMap.getMap(WifiFunctionActivity.this, "wifiInfo");          // 取到保存过的wifi
        List<ScanResult> list = m_wifiAdmin.getWifiList();
        if (list == null) {
            m_scanResultList.clear();
        } else {
            m_scanResultList = list;
            if (m_wifiAdmin.isWifiConnect(this)) {                                        // wifi已连接状态
                isUpDate = false;                                                         // 设置为false停止刷新列表
                return;
            } else {
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        autoConnWifi();                                                  // 自动连接wifi
//                        try {
//                            Thread.sleep(2000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }).start();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        m_wifiAdmin.Dispose(WifiFunctionActivity.this);
    }
}
